import React, { Component } from 'react'
import { Button,Alert } from 'antd'

export default class Father extends Component {
  array = [...Array(5)].map((item,index) => ({id : index, name: `第${index+1}项`}))
  state = { list: this.array, hasError: false }
  onNormalShow = () => {
    this.setState({ list: this.array })
  }
  onErrorShow = () => {
    this.setState({ list: 1 })
  }

  //报错后，视图更新前调用
  static getDerivedStateFromError(error) {
    console.log('getDerivedStateFromError',error);
    
		return {list: [], hasError: true} //返回一个对象，进行修改该组件的 state状态
  }

  //报错后，视图更新后调用
  componentDidCatch() {
    console.log('componentDidCatch','此处统计错误，反馈给服务器，用于通知编码人员进行bug的解决');
  }

  render() {
    return (
      <div>
        <Button onClick={this.onNormalShow}>正常显示</Button>
        <Button onClick={this.onErrorShow}>错误显示</Button>
        {/* 在开发模式下，通过getDerivedStateFromError进行页面降级(切换备用页面)，依然会报错。正式打包运行就正常显示备用页面 */}
        { this.state.hasError ? <Alert message="Error Text" type="error" /> : <Son list={this.state.list}/> } 
      </div>
    )
  }
}

function Son(props) {
  return (
    <div>
      {props.list.map(item => <h4 key={item.id}>{item.name}</h4>)}
    </div>
  )
}
